<template>
  <el-form
    ref="formRef"
    :model="form"
    :rules="rules"
    label-width="100px"
    class="role-form"
  >

    <el-form-item label="角色名称" prop="roleName">
      <el-input v-model="form.roleName" placeholder="请输入角色名称" />
    </el-form-item>

    <el-form-item label="角色图标">
      <el-upload
        :action="uploadAction"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :on-remove="handleRemove"
        :before-upload="beforeUpload"
        list-type="picture-card"
        :file-list="fileList"
        :limit="1"
        :on-exceed="handleExceed"
        :headers="uploadHeaders"
      >
        <el-icon><Plus /></el-icon>
        <template #tip>
          <div class="el-upload__tip">支持jpg、png格式</div>
        </template>
      </el-upload>
      <el-image
        v-if="form.roleLogo"
        :src="form.roleLogo"
        style="width: 100px; height: 100px; margin-top: 10px"
        fit="cover"
      />
    </el-form-item>

    <el-form-item label="角色描述" prop="roleDes">
      <el-input
        v-model="form.roleDes"
        type="textarea"
        rows="4"
        placeholder="请输入角色描述信息"
      />
    </el-form-item>

    <el-form-item label="角色状态" prop="status">
      <el-switch
        v-model="form.status"
        :active-value="1"
        :inactive-value="0"
        active-text="启用"
        inactive-text="禁用"
      />
    </el-form-item>

    <el-form-item label="角色权限" prop="permissions">
      <el-select
        v-model="form.permissions"
        multiple
        placeholder="请选择角色拥有的权限"
        style="width: 100%"
      >
        <el-option
          v-for="permission in permissionList"
          :key="permission.id"
          :label="permission.permissionName"
          :value="permission.id"
        />
      </el-select>
    </el-form-item>

    <el-form-item>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSubmit">保存</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { reactive, ref, watch, onMounted, computed } from 'vue'
import { getPermissions } from '@/api/permission'
import { addRole, updateRole, assignRolePermissions } from '@/api/permission'
import { useUserStore } from '@/stores/user'

// 接收父组件传入的角色数据
const props = defineProps({
  modelValue: {
    type: Object,
    default: () => ({})
  }
})

// 向父组件传递事件
const emit = defineEmits(['save', 'cancel'])

// 表单引用
const formRef = ref(null)

// 表单数据
const form = reactive({
  id: '',
  roleName: '',
  roleLogo: '',
  roleDes: '',
  status: 1, // 修改为数字类型
  permissions: []
})

// 权限列表
const permissionList = ref([])

// 上传文件列表
const fileList = ref([])

// 上传相关配置
const uploadAction = computed(() => {
  return '/api/order/order-client/api/file/upload'
})

const uploadHeaders = computed(() => {
  const userStore = useUserStore()
  const token = userStore.userInfo?.userInfoVO?.token
  return token ? { Authorization: `Bearer ${token}` } : {}
})

// 监听传入的角色数据变化
watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      // 复制基础信息
      form.id = val.roleId || ''
      form.roleName = val.roleName || ''
      form.roleLogo = val.roleLogo || ''
      form.roleDes = val.roleDes || ''
      form.status = val.status !== undefined ? Number(val.status) : 1 // 使用数字类型

      // 处理权限数据
      const permissionIds = val.permissions
        ? val.permissions.map(perm => String(perm.id))
        : []

      form.permissions = permissionIds

      // 初始化头像文件列表
      if (val.roleLogo) {
        fileList.value = [{ url: val.roleLogo, name: '角色图标' }]
      } else {
        fileList.value = []
      }
    }
  },
  { immediate: true }
)

// 表单验证规则
const rules = {
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '角色名称长度在 2 到 20 个字符之间', trigger: 'blur' }
  ],
  roleDes: [
    { max: 200, message: '角色描述不能超过200个字符', trigger: 'blur' }
  ],
  permissions: [
    { required: true, message: '请至少选择一个权限', trigger: 'change' }
  ]
}

// 获取所有权限列表
const fetchPermissions = async () => {
  try {
    const response = await getPermissions({ pageSize: 100 })
    permissionList.value = response.data.records.map(p => ({
      ...p,
      id: String(p.id)
    }))
    console.log('Permission list loaded:', permissionList.value)
  } catch (error) {
    ElMessage.error('获取权限列表失败')
    console.error(error)
  }
}

// 文件上传前检查
const beforeUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'

  if (!isJPG) {
    ElMessage.error('上传图标只能是 JPG/PNG 格式!')
    return false
  }
  return true
}

// 处理上传成功
const handleUploadSuccess = (response, uploadFile) => {
  console.log('上传响应:', response)
  if (response && response.code === 0 && response.data) {
    // 处理返回的数据，确保正确获取图片URL
    if (typeof response.data === 'string') {
      // 直接返回URL字符串
      form.roleLogo = response.data
      fileList.value = [{
        name: uploadFile.name,
        url: response.data
      }]
    } else if (response.data.url) {
      // 返回包含url字段的对象
      form.roleLogo = response.data.url
      fileList.value = [{
        name: response.data.name || uploadFile.name,
        url: response.data.url
      }]
    } else if (response.data.path) {
      // 处理可能返回path字段的情况
      form.roleLogo = response.data.path
      fileList.value = [{
        name: response.data.name || uploadFile.name,
        url: response.data.path
      }]
    }
    ElMessage.success('图标上传成功')
  } else {
    ElMessage.error('图标上传失败: ' + (response?.msg || '未知错误'))
  }
}

// 处理上传失败
const handleUploadError = (error) => {
  console.error('图标上传失败', error)
  ElMessage.error('图标上传失败: ' + (error.message || '未知错误'))
}

// 文件超出限制
const handleExceed = () => {
  ElMessage.warning('只能上传一张图标')
}

// 移除图片
const handleRemove = (uploadFile, uploadFiles) => {
  form.roleLogo = ''
  fileList.value = []
}

// 取消操作
const handleCancel = () => {
  emit('cancel')
  emit('update:visible', false)
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()

    const roleData = {
      roleName: form.roleName,
      roleLogo: form.roleLogo || '',  // 确保传递图标路径，如果没有则传递空字符串
      roleDes: form.roleDes,
      status: form.status
    }

    let roleId
    let roleResponse

    if (form.id) {
      roleResponse = await updateRole(form.id, roleData)
      roleId = form.id
      ElMessage.success('角色信息更新成功')
    } else {
      roleResponse = await addRole(roleData)
      roleId = roleResponse.data.id
      ElMessage.success('角色创建成功')
    }

    if (form.permissions && form.permissions.length > 0) {
      try {
        await assignRolePermissions({
          roleId: roleId,
          permissionIds: form.permissions
        })
        ElMessage.success('角色权限分配成功')
      } catch (permissionError) {
        console.error('Permission assignment error:', permissionError)
        const errorMsg = permissionError.msg || permissionError.message || '角色权限分配失败'
        ElMessage.error('角色权限分配失败: ' + errorMsg)
      }
    } else {
      ElMessage.success('保存成功')
    }

    emit('save')
  } catch (error) {
    if (error.errors) {
      const errorMsg = Object.values(error.errors).flat().join('；')
      ElMessage.error(errorMsg || '表单验证失败，请检查输入')
    } else {
      ElMessage.error('保存失败，请重试: ' + (error.msg || error.message || '未知错误'))
      console.error(error)
    }
  }
}

// 页面加载时获取权限列表
onMounted(() => {
  fetchPermissions()
})
</script>

<style scoped>
.role-form {
  margin-top: 20px;
}

::v-deep .el-form-item {
  margin-bottom: 15px;
}
</style>
